package mspbots.data.tl.script.entity;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * @author Jay.Yang
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ScriptAction {
    private final ObjectMapper objectMapper;
    private final RestTemplate restTemplate;
    @Value("${mspbots.web.url}")
    private String webUrl = "https://appint.mspbots.ai";
    private static RestTemplate sRestTemplate;
    private static ObjectMapper sObjectMapper;

    public static JsonNode sendTeamsMessage(TeamsMessageDTO teamsMessageDTO) {
        return call("notice-bot", "/teams/message/send", "post", teamsMessageDTO);
    }

    public static JsonNode call(String server, String url) {
        return call(server, url, null);
    }

    public static JsonNode call(String server, String url, Map<String,Object> params) {
        String uri = "http://" + server + url;
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(uri);
        params.entrySet().stream().forEach(o -> builder.queryParam(o.getKey(),o.getValue()));
        String urlBuild = builder.build().encode().toString();
        return sRestTemplate.getForObject(urlBuild,JsonNode.class,params);
    }

    public static JsonNode call(String server, String url, String methodType, Object params) {
        log.debug("api call params: {} {} {} {}", server, url, methodType, params);
        String uri = "http://" + server + url;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_VALUE));
        HttpEntity<MultiValueMap<String, Object>> entity = null;
        try {
            entity = new HttpEntity(sObjectMapper.writeValueAsString(params), headers);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        JsonNode result = sRestTemplate.exchange(uri, HttpMethod.POST, entity, JsonNode.class).getBody();
        log.debug("api call result: {}", result);
        return result;
    }

    @PostConstruct
    public void init() {
        sRestTemplate = restTemplate;
        sObjectMapper = objectMapper;
    }
}
